//
//  VideoUtils.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/8.
//

import Foundation
import AVFoundation

struct VideoInfo {
    let duration: Double
    let width: CGFloat
    let height: CGFloat
}

// 扩展方法
extension CGAffineTransform {
    func isPortraitOrientation(videoSize: CGSize) -> Bool {
        // 通过旋转角度判断方向
        let rotation = atan2(self.b, self.a)
        let degree = rotation * 180 / .pi
        
        // 当旋转角度为 90° 或 270° 时视为竖屏
        return abs(degree) == 90 || abs(degree) == 270
    }
}

func getVideoInfo(from url: URL) async -> VideoInfo? {
    let asset = AVURLAsset(url: url)
    
    do {
        let duration = try await asset.load(.duration).seconds
        let tracks = try await asset.load(.tracks)
        
        guard let videoTrack = tracks.first(where: { $0.mediaType == .video }) else {
            return nil
        }
        
        let naturalSize = try await videoTrack.load(.naturalSize)
        let transform = try await videoTrack.load(.preferredTransform)
        
        // 使用修正后的方向判断
        let isPortrait = transform.isPortraitOrientation(videoSize: naturalSize)
        let width = isPortrait ? naturalSize.height : naturalSize.width
        let height = isPortrait ? naturalSize.width : naturalSize.height
        
        return VideoInfo(
            duration: duration,
            width: width,
            height: height
        )
    } catch {
        showLog("Error: \(error.localizedDescription)")
        return nil
    }
}




    // 将本地视频转换为 Data（注意内存管理）
    func convertVideoToData(url: URL) throws -> Data {
        // 重要：先检查文件大小
        let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
        guard let fileSize = attributes[.size] as? Int64 else {
            throw NSError(domain: "FileError", code: 0, userInfo: [NSLocalizedDescriptionKey: "无法获取文件大小"])
        }
        
        // 安全阈值：建议不超过 100MB
        if fileSize > 100 * 1024 * 1024 {
            throw NSError(domain: "FileError", code: 0, userInfo: [NSLocalizedDescriptionKey: "文件过大，请使用分片上传"])
        }
        
        do {
            // 使用安全作用域访问
            let accessed = url.startAccessingSecurityScopedResource()
            defer {
                if accessed {
                    url.stopAccessingSecurityScopedResource()
                }
            }
            
            return try Data(contentsOf: url, options: .mappedIfSafe)
        } catch {
            throw error
        }
    }
    // 分块读取大文件（推荐方式）
    func readVideoInChunks(url: URL, chunkSize: Int = 5 * 1024 * 1024) throws -> [Data] {
        let accessed = url.startAccessingSecurityScopedResource()
        defer {
            if accessed {
                url.stopAccessingSecurityScopedResource()
            }
        }
        
        let fileHandle = try FileHandle(forReadingFrom: url)
        defer { fileHandle.closeFile() }
        
        var chunks = [Data]()
        while true {
            let data = fileHandle.readData(ofLength: chunkSize)
            if data.isEmpty { break }
            chunks.append(data)
        }
        return chunks
    }
